﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.Linq;
using System.Collections;
using System.ComponentModel;
using System.Net;
using System.Text;
using System.Collections.Generic;

namespace HtmlMaker
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                string d = folderBrowserDialog1.SelectedPath;
                if (new DirectoryInfo(d).Exists)
                {
                    views(new DirectoryInfo(d));
                    comboBox1.Text = d;
                    comboBox1.Items.Insert(0, d);
                    saveHistorys(d);
                }
            }
        }

        private void saveHistorys(string d)
        {
            if (appSettings != null)
            {
                if (appSettings.OpenedHistory == null)
                {
                    appSettings.OpenedHistory = new System.Collections.Generic.List<string>();
                }
                if (appSettings.OpenedHistory.Contains(d))
                {
                    appSettings.OpenedHistory.Remove(d);
                }
                appSettings.OpenedHistory.Add(d);
            }
        }

        private static AppSettings appSettings;
        private string APP_SETTINGS_PATH = Application.StartupPath + @"\app.settings";
        private BackgroundWorker loadDataWorker;

        private void Form1_Load(object sender, EventArgs e)
        {
            if (File.Exists(APP_SETTINGS_PATH))
            {
                FileStream fs1 = new FileStream(Application.StartupPath + @"\app.settings", FileMode.Open, FileAccess.Read);
                BinaryFormatter bff = new BinaryFormatter();
                appSettings = (AppSettings)bff.Deserialize(fs1);
                fs1.Close();
                textBox1.Text = appSettings.Output;
            }
            else
            {
                appSettings = new AppSettings();
            }

            if (appSettings == null)
            {
                throw new Exception("appSettings == null");
            }

            if (appSettings.OpenedHistory != null && appSettings.OpenedHistory.Count > 0)
            {
                comboBox1.Text = appSettings.OpenedHistory[appSettings.OpenedHistory.Count - 1];
                foreach (string s in appSettings.OpenedHistory)
                {
                    comboBox1.Items.Add(s);
                }
            }
            else
            {
                comboBox1.Text = "C:\\";
            }

            if (appSettings.dataSources != null && appSettings.dataSources.Count > 0)
            {
                Hashtable ht = appSettings.dataSources;
                IDictionaryEnumerator emt = ht.GetEnumerator();
                while (emt.MoveNext())
                {
                    ListViewItem ls = lvDataSource.Items.Add(emt.Key.ToString());
                    ls.SubItems.Add(emt.Value.ToString());
                }
            }

            views(new DirectoryInfo(comboBox1.Text));

            loadDataWorker = new BackgroundWorker();
            loadDataWorker.DoWork += new DoWorkEventHandler(loadDataWorker_DoWork);
            loadDataWorker.RunWorkerAsync(appSettings.dataSources);
        }

        void loadDataWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Hashtable ht = e.Argument as Hashtable;
            PageBuilder.ds = new Hashtable();
            IDictionaryEnumerator emt = ht.GetEnumerator();
            while (emt.MoveNext())
            {
                Hashtable[] _ht = Newtonsoft.Json.JsonConvert.DeserializeObject<Hashtable[]>(GetByUrl(emt.Value.ToString()));
                PageBuilder.ds.Add(emt.Key.ToString(), _ht);
            }
        }

        private string GetByUrl(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader myreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            return myreader.ReadToEnd();
        }

        public void views(DirectoryInfo directorys)
        {
            try
            {
                DirectoryInfo[] ds = directorys.GetDirectories();
                FileInfo[] fs = directorys.GetFiles();
                listView1.Items.Clear();

                foreach (DirectoryInfo d in ds)
                {
                    ListViewItem ls = listView1.Items.Add(d.Name);
                    ls.Tag = d.FullName;
                    ls.ImageIndex = 0;
                }

                foreach (FileInfo f in fs)
                {
                    Icon cc = GetSystemIco.GetIconByFileName(f.FullName);
                    imageList2.Images.Add(f.Name, cc);

                    ListViewItem ls = listView1.Items.Add(f.Name);
                    ls.Tag = f.FullName;
                    ls.ImageKey = f.Name;
                }
                comboBox1.Text = directorys.FullName;
            }
            catch { }
        }

        private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                string d = comboBox1.Text;
                if (new DirectoryInfo(d).Exists)
                {
                    views(new DirectoryInfo(d));
                }
                else { MessageBox.Show("没有此目录", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string d = comboBox1.Text;
            if (new DirectoryInfo(d).Exists)
            {
                saveHistorys(d);
                views(new DirectoryInfo(d));
            }
            else { MessageBox.Show("没有此目录", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); }
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                string newpath = listView1.SelectedItems[0].Tag.ToString();
                if (Directory.Exists(newpath))
                {
                    views(new DirectoryInfo(newpath));
                }
                else
                {
                    Process.Start(newpath);
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.ToString()); }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(comboBox1.Text);
                if (dir.Parent != null)
                {
                    string xname = dir.Parent.FullName;
                    views(new DirectoryInfo(xname));
                }
            }
            catch { }
        }

        private void listView1_DragDrop(object sender, DragEventArgs e)
        {
            string natp = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            string name = natp.Substring(natp.LastIndexOf("\\") + 1);
            File.Copy(natp, comboBox1.Text + name, true);
            views(new DirectoryInfo(comboBox1.Text));
        }

        private void listView1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            views(new DirectoryInfo(comboBox1.Text));
        }

        void dele()
        {
            try
            {
                DialogResult aa = MessageBox.Show("确定删除？", "提示", MessageBoxButtons.YesNo);
                if (aa == DialogResult.Yes)
                {
                    foreach (ListViewItem item in listView1.SelectedItems)
                    {
                        string xpath = item.Tag.ToString();
                        if (File.Exists(xpath))
                        {
                            File.Delete(xpath);
                            views(new DirectoryInfo(comboBox1.Text));
                        }
                        else
                        {
                            DirectoryInfo dd = new DirectoryInfo(xpath);
                            dd.Delete();
                            views(new DirectoryInfo(comboBox1.Text));
                        }
                    }
                }

            }
            catch (Exception ex) { MessageBox.Show(ex.ToString()); }
        }
        private void 删除ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            dele();
        }

        private void 重命名ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            listView1.LabelEdit = true;
            listView1.SelectedItems[0].BeginEdit();//点击重命名的时候可以编辑
        }

        private void contextMenuStrip1_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Point point = listView1.PointToClient(Cursor.Position);
            ListViewItem item = listView1.GetItemAt(point.X, point.Y);   //获得鼠标坐标处的ListViewItem
            if (item == null) //没在
            {
                DELToolStripMenuItem1.Visible = false;
                SXToolStripMenuItem.Visible = true;
            }

            else//在
            {
                SXToolStripMenuItem.Visible = false;
                DELToolStripMenuItem1.Visible = true;
            }
        }

        private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            Process.Start("cmd", "/c" + "ren " + listView1.SelectedItems[0].Tag.ToString() + " " + e.Label.ToString() + "");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog2.ShowDialog() == DialogResult.OK)
            {
                string d = folderBrowserDialog2.SelectedPath;
                if (new DirectoryInfo(d).Exists)
                {
                    textBox1.Text = d;
                    appSettings.Output = d;
                }
            }
        }

        private void 扫描当前项目ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 添加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            addDataSource ads = new addDataSource();
            DialogResult rtl = ads.ShowDialog();
            if (rtl == System.Windows.Forms.DialogResult.OK)
            {
                ListViewItem ls = lvDataSource.Items.Add(ads.name);
                ls.SubItems.Add(ads.url);
            }            
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (appSettings != null)
            {
                appSettings.dataSources = new System.Collections.Hashtable();
                if (lvDataSource.Items.Count > 0)
                {
                    foreach (ListViewItem item in lvDataSource.Items)
                    {
                        appSettings.dataSources.Add(item.SubItems[0].Text, item.SubItems[1].Text);
                    }
                }

                FileStream fs = new FileStream(APP_SETTINGS_PATH, FileMode.Create, FileAccess.Write);
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, appSettings);
                fs.Close();
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult aa = MessageBox.Show("确定删除？", "提示", MessageBoxButtons.YesNo);
                if (aa == DialogResult.Yes)
                {
                    foreach (ListViewItem item in lvDataSource.SelectedItems)
                    {
                        lvDataSource.Items.Remove(item);
                    }
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.ToString()); }
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lvDataSource.SelectedItems.Count > 0)
            {
                System.Diagnostics.Process.Start(lvDataSource.SelectedItems[0].SubItems[1].Text);
            }
        }

        private void 生成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string toDir = textBox1.Text.Trim();
            if (string.IsNullOrEmpty(toDir) || !Directory.Exists(toDir))
            {
                MessageBox.Show("请在[配置]中指定生成文件的存放路径！");
                return;
            }

            foreach (ListViewItem item in listView1.SelectedItems)
            {
                string xpath = item.Tag.ToString();

                if (File.Exists(xpath))
                {
                    FileInfo info = new FileInfo(xpath);
                    ListViewItem ls = listView2.Items.Add(info.Name);
                    ls.SubItems.Add((info.Length / 1024).ToString());
                    ls.SubItems.Add(info.LastWriteTime.ToLocalTime().ToString());
                    ls.Tag = info.FullName;
                    ls.ImageIndex = 0;

                    string strFile = PageBuilder.Format(xpath, appSettings.dataSources, ls);

                    FileStream nFile = new FileStream(appSettings.Output + "\\" + info.Name, FileMode.Create);
                    StreamWriter writer = new StreamWriter(nFile);
                    writer.Write(strFile);
                    writer.Close();
                }
                else
                {
                    DirectoryInfo dd = new DirectoryInfo(xpath);
                }
            }
            listView2.Visible = true;
        }

        private void 更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
    }
}
